<?php
declare (strict_types=1);

namespace app\admin\model\iot;

use app\BaseModel;
use iot\DeviceClient;

/**
 * 设备Apk升级日志表
 */
class DeviceApkLog extends BaseModel
{

    /**
     * 获取设备Apk升级日志列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @param string $orderby
     * @return array
     */
    public static function getList(array $where, int $page, int $limit, string $orderby = ''): array
    {
        $data = self::where($where)
            ->order($orderby)
            ->paginate(['list_rows' => $limit, 'page' => $page], false)
            ->toArray();
        return $data;
    }

    /**
     * 写入设备Apk升级
     * @param array $msg
     * @return bool
     */
    public static function writeApkUpgrade(array $msg): bool
    {
        //获取设备imei
        $field = 'imei,type,apk';
        $device = Device::findOne(['mac_id' => $msg['mac_id']], $field);
        if (!$device) {
            return false;
        }
        //判断类型
        if ($device['type'] != $msg['type']) {
            return false;
        }
        //组装数据
        $temp = [
            'apk_id' => $msg['id'],
            'imei' => $device['imei'],
            'req_id' => uuid(),
            'old_ver' => $device['apk'],
            'new_ver' => $msg['version'],
            'result' => '发布升级',
            'create_time' => time(),
            'update_time' => time(),
        ];
        self::insert($temp);
        //发送指令
        $run = DeviceClient::getInstance();
        $run->apkUpgrade($device['imei'], $temp['req_id'], $device['type'], $msg['version'], $msg['src']);
        return true;
    }

    /**
     * 更新升级日志
     * @param string $req_id
     * @param string $result
     * @return DeviceApkLog
     */
    public static function updateApkLog(string $req_id, string $result): DeviceApkLog
    {
        $where = ['req_id' => $req_id];
        $data = ['result' => $result, 'update_time' => time()];
        return self::update($data, $where);
    }

}




